package pl.edu.agh.ros.node;

import org.ros.exception.RemoteException;
import org.ros.node.DefaultNodeFactory;
import org.ros.node.Node;
import org.ros.node.NodeConfiguration;
import org.ros.node.NodeMain;
import org.ros.node.service.ServiceClient;
import org.ros.node.service.ServiceResponseListener;
import org.ros.service.test_ros.AddTwoInts;
import org.ros.service.test_ros.AddTwoInts.Request;

import com.google.common.base.Preconditions;

public class RosServiceClient implements NodeMain {

	private static int instanceNr = 0;
	private long resp;

	private static final String SERVICE_NAME = "/test_service"; //$NON-NLS-1$
	private static final String SERVICE_TYPE = "test_ros/AddTwoInts"; //$NON-NLS-1$
	private final int number;
	private Node node;

	public RosServiceClient(int number) {
		this.number = number;
	}

	@Override
	public void main(NodeConfiguration configuration) {
		Preconditions.checkState(node == null);
		Preconditions.checkNotNull(configuration);
		try {
			System.out.println("Starting a Testing Service Client Node........"); //$NON-NLS-1$
			node = new DefaultNodeFactory().newNode("test_service_client" + instanceNr++, configuration); //$NON-NLS-1$

			ServiceClient<AddTwoInts.Request, AddTwoInts.Response> client = node.newServiceClient(SERVICE_NAME,
					SERVICE_TYPE);
			AddTwoInts addTwoInts = new AddTwoInts();
			final Request addTwoIntsRequest = addTwoInts.createRequest();
			addTwoIntsRequest.a = 0;
			addTwoIntsRequest.b = number;
			client.call(addTwoIntsRequest, new ServiceResponseListener<AddTwoInts.Response>() {
				@Override
				public void onSuccess(AddTwoInts.Response response) {
					System.out.println("The sum of: " + addTwoIntsRequest.a + " and " + addTwoIntsRequest.b + " is " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
							+ response.sum);
					resp = response.sum;
				}

				@Override
				public void onFailure(RemoteException e) {
					System.out.println("Request failure"); //$NON-NLS-1$
				}
			});

		} catch (Exception e) {
			if (node != null) {
				node.getLog().fatal(e);
			} else {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void shutdown() {
		node.shutdown();
		node = null;
	}

	public long getResp() {
		return resp;
	}

}
